package com.jcj.pojomessagepack;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import org.msgpack.MessagePack;

import java.util.List;

/**
 * 通过扩展MessageToMessageDecoder来自定义解码器,基于MessagePack的解码器,把byte数组反序列化为消息实体对象
 */
public class MessagePackDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {

        MessagePack messagePack = new MessagePack();
        //字节序列的长度
        int intLength = byteBuf.readableBytes();
        byte[] raw = new byte[intLength];
        //byteBuf.readerIndex():读取起点的索引,读到raw中
        byteBuf.getBytes(byteBuf.readerIndex(),raw,0,intLength);

        //messagePack.read,不指明实体,list存的是每个属性的value
        //list.add(messagePack.read(raw));

        //messagePack.read,指明实体,list存的是实体对象的集合
        list.add(messagePack.read(raw,Infomation.class));


    }
}
